// 创建axios实例
import axios from "axios";
import {delCookie, getCookie} from "./cookieUtil";
import commonUtil, {ECode} from "./commonUtil";
import {message} from "ant-design-vue";
import {cookieToken} from "@/config/CookieConfig";
import {loginConfigStore} from "@/store/user/loginConfigStore";
import {v4 as uuidV4} from 'uuid';

const service = axios.create({
    baseURL: '', // api 的 base_url
    timeout: 100000 // 请求超时时间
})

// token的消息头
const TOKEN_HEADER: string = 'Authorization';

// 传递token
service.defaults.headers.common['Authorization'] = getCookie(cookieToken)

// request拦截器
service.interceptors.request.use(
    config => {
        const token = getCookie(cookieToken);
        if (token) {
            // 让每个请求携带自定义token 请根据实际情况自行修改
            config.headers[TOKEN_HEADER] = token;
        } else {
            delete config.headers[TOKEN_HEADER];
        }
        if (getCookie("validCode") !== undefined) {
            config.headers.validCode = getCookie("validCode")
        }
        let value = 2000000000000 - Date.parse(new Date().toUTCString())
        config.headers.Pragmas = String(value)
        return config
    },
    error => {
        Promise.reject(error).then(() => {
            message.warn('请求拦截')
        })
    }
)
// response 拦截器
service.interceptors.response.use(
    response => {
        /**
         * code为非success和error是抛错 可结合自己业务进行修改
         */
        const res = response.data
        const code: number | string = res.code || 'success';
        // 二进制数据则直接返回
        if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
            return res;
        }
        // 获取错误信息
        const errorCode = commonUtil.errorCode
        //@ts-ignore
        const msg = errorCode[code] || res.message || res.msg || errorCode['default']

        if (code === ECode.SUCCESS) {
            // 请求完毕
            return res
        }
        if (code === ECode.ERROR && msg == ECode.WECHAT_POLLING) {
            return res
        } else if (code === ECode.ERROR && msg !== ECode.WECHAT_POLLING) {
            message.error(msg);
            return Promise.reject(new Error(msg))
        } else {
            if (code === 401) {
                message.error('Token已过期，请重新登录').then(() => {
                    if (getCookie(cookieToken)) {
                        delCookie(cookieToken)
                    }
                    loginConfigStore().setLoginMessage(uuidV4())
                })
                return Promise.reject('error')
            } else if (code === 402 || code === 403) {
                message.error(msg)
                return Promise.reject(new Error(msg));
            } else {
                message.error(msg)
                return Promise.reject(new Error(msg));
            }
        }
    },
    error => {
        let {respInfo} = error;
        if (respInfo) {
            if (respInfo === "Network Error") {
                respInfo = "后端接口连接异常";
            } else if (respInfo.includes("timeout")) {
                respInfo = "系统接口请求超时";
            } else if (respInfo.includes("Request failed with status code")) {
                respInfo = "系统接口异常,errorCode[" + respInfo.substr(respInfo.length - 3) + "]";
            }
        }
        message.error(respInfo)
        return Promise.reject(error)
    }
)

export default service
